<template>
  <view class="image-upload">
    <view class="button">
      <image class="image" src="/static/images/upload-image.png" @click="upload" ></image>
      <view class="progress">
        <progress :percent="percent" active stroke-width="3" />
      </view>
    </view>
    <view class="items">
      <image
          class="item"
          v-for="(image, index) in currentImages"
          :key="index"
          :src="image"
      ></image>
    </view>
		<view class="img-clear" @click="clearImg()">图片清除</view>
  </view>
</template>

<script>
import store from "store";
import { mapGetters, mapActions } from 'vuex'
import Base64 from 'base-64';
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1;
let day = date.getDate()
let signNum = Base64.encode((year + month * 2 + day * 3) * 2)

export default {
  name: "ImageUploadCom",
  data: () => ({
    percent: 0,
    currentImages: []
  }),
  computed: {
    ...mapGetters(['uploadImages'])
  },
  methods: {
    ...mapActions(['updateUploadImages']),
    upload() {
			this.percent = 0
      uni.chooseImage({
        count: 1,
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          const uploadTask = uni.uploadFile({
						url:this.uploadUrl,
            // url: 'https://shopdev.littleshop.shop/api/v1/files',//测试
            // url: 'https://shop.littleshop.shop/api/v1/files', //正式
            method: 'post',
            filePath: tempFilePaths[0],
            name: 'image',
            header: {
							Authorization: 'Bearer ' + store.getters.accessToken,
							sign:signNum
						},
            success: async (uploadFileRes) => {
              let image = JSON.parse(uploadFileRes.data)
              this.currentImages.push(image.image)
              await this.updateUploadImages(this.currentImages)
            }
          });

          uploadTask.onProgressUpdate((res) => {
            this.percent = res.progress
            //console.log('已经上传的数据长度' + res.totalBytesSent);
            //console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
          })
        }
      })
    },
		clearImg(){
			this.currentImages = []
		}
  }
}
</script>

<style lang="scss" scoped>
.image-upload {
  .button {
    margin-bottom: 10rpx;
    .image {
      width: 150rpx;
      height: 150rpx;
	  margin-top:18rpx;
    }
    .progress {
      width: 140rpx;
      height: 10rpx;
    }
  }
  .items {
    display: flex;
    flex-wrap: wrap;
    .item {
      width: 140rpx;
      height: 140rpx;
      border-radius: 5rpx;
      border: 1px #EEEEEE solid;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }
}
.img-clear{
	width: 126rpx;
	height: 29rpx;
	border-radius: 4rpx;
	font-size: 18rpx;
	color:#999;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 2rpx solid #999999;
	margin:8rpx 0 10rpx 10rpx;
	padding-left:6rpx;
}
</style>
